import numpy as np
from scipy.optimize import leastsq

f= open("data.txt")
data = f.read().split('\n')
f.close()
for i in data:
    data[data.index(i)]=i.split(',')
    
listx = []
listy = []

for i in data:
    listx.append(i[0])
    listy.append(i[1])

#print(listx[0])
for i in listx:
    listx[listx.index(i)] = float(i)
for i in listy:
    listy[listy.index(i)] = float(i)

#print(type(listx[2]))
###############################################################################    

xi = np.array(listx)
yi = np.array(listy)

def func(p,x):
    k,b=p
    return k*x + b


def error(p,x,y):
    return func(p,x)-y

p0 = [1,20]
Para=leastsq(error,p0,args=(xi,yi))
k,b=Para[0]
print('k=',k,'  ','b=',b)
print('cost:',str(Para[1]))
print('公式是：','y='+str(round(k,2))+'x+'+str(round(b,2)))

